package cn.comtom.ewbs.signature.controller;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.aizuda.monitor.OshiMonitor;
import com.alibaba.fastjson.JSON;
import com.wf.captcha.utils.CaptchaUtil;

import cn.comtom.ewbs.signature.QuickStartApplication;
import cn.comtom.ewbs.signature.common.enums.BasicError;
import cn.comtom.ewbs.signature.common.enums.SysConstant;
import cn.comtom.ewbs.signature.common.vo.dto.SysMenu;
import cn.comtom.ewbs.signature.common.vo.request.LoginRequest;
import cn.comtom.ewbs.signature.common.vo.response.ApiEntityResponse;
import cn.comtom.ewbs.signature.common.vo.response.ApiResponse;
import cn.comtom.ewbs.signature.common.vo.response.ApiResponseBuilder;
import cn.comtom.ewbs.signature.entity.SysUser;
import cn.comtom.ewbs.signature.service.ISysPermissionService;
import cn.comtom.ewbs.signature.service.ISysUserService;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.thread.ThreadUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 后台方法
 * 
 * @ClassName: HomeController
 * @author fuce
 * @date 2019-10-21 00:10
 *
 */
@Controller
@RequestMapping("/auth/admin")
@Slf4j
public class AdminController extends AuthController {

	private String prefix = "admin";
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private ISysPermissionService sysPermissionService;
	
	@Resource
	private OshiMonitor oshiMonitor;

	
	@ApiOperation(value = "首页", notes = "首页")
	@GetMapping({"", "/index"})
	public String index(HttpServletRequest request) {
		request.getSession().setAttribute("sessionUserName", getCurrentUserInfo().getUserName());
		// 获取公告信息
		return prefix + "/index";
	}
	
    @PostMapping(value="/restart")
    @ApiOperation(value = "重启服务", notes = "重启服务")
    @ResponseBody
    public ApiResponse restart() {
    	Executors.newScheduledThreadPool(1).schedule(new Runnable() {
			@Override
			public void run() {
				QuickStartApplication.restart();
			}
		}, 2, TimeUnit.SECONDS);
    	return ApiResponse.ok();
    }
	
	/**
	 * 展示页面
	 *
	 * @param model
	 * @return
	 * @author fuce
	 * @Date 2019年11月11日 下午4:04:03
	 */
	@ApiOperation(value = "展示页面", notes = "展示页面")
	@GetMapping("/view")
	//@SaCheckPermission("system:service:view")
	public String view(ModelMap model) {
		/*List<SysNotice> sysNotices = sysNoticeService.getNEW();
		List<TsysOperLog> sysOperLog = sysOperLogService.getNEW();
		if (sysNotices == null || sysNotices.size() <= 0) {
			SysNotice sysNotice = new SysNotice();
			sysNotice.setId("0");
			sysNotice.setTitle("暂无公告");
			sysNotice.setCreateTime(new Date());
			sysNotices.add(sysNotice);
		}*/

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = oshiMonitor.getJvmInfo().getUptime();
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		//long sec = diff % nd % nh % nm / ns;

		model.addAttribute("runtime", day + "天" + hour + "小时" + min + "分钟");
		model.addAttribute("service", oshiMonitor);
		//model.addAttribute("sysNotices", sysNotices);
		//model.addAttribute("sysOperLog", sysOperLog);
		return prefix + "/service/view";
	}




	@ApiOperation(value = "获取登录用户菜单栏", notes = "获取登录用户菜单栏")
	@GetMapping("/getUserMenu")
	@ResponseBody
	public List<SysMenu> getUserMenu(){
		List<SysMenu> sysMenus=sysPermissionService.getSysMenus(getCurrentUserInfo().getId());
		return sysMenus;
	}




	/**
	 * 请求到登陆界面
	 * 
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "请求到登陆界面", notes = "请求到登陆界面")
	@GetMapping("/login")
	public String login(ModelMap modelMap) {
		try {
			if (StpUtil.isLogin()) {
				return "redirect:/" + prefix + "/index";
			} else {
				System.out.println("--进行登录验证..验证开始");
				modelMap.put("RollVerification", true);
				System.out.println("V2Config.getRollVerification()>>>" + true);
				return "login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "login";
	}
	
	/**
	 * 用户登陆验证
	 * @param user
	 * @param rcode
	 * @param redirectAttributes
	 * @param rememberMe
	 * @param model
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "用户登陆验证", notes = "用户登陆验证")
	@PostMapping("/login")
	@ResponseBody
	public ApiEntityResponse<SysUser> login(LoginRequest user, String captcha, RedirectAttributes redirectAttributes, boolean rememberMe,
			HttpServletRequest request) {
		// ModelAndView view =new ModelAndView();
		Boolean yz = false;
		// 获取session中的验证码
		String verCode = (String) request.getSession().getAttribute("captcha");
		 // 判断验证码
		if (captcha!=null && captcha.toLowerCase().equals(verCode.trim().toLowerCase())) {
			//清除验证码
			CaptchaUtil.clear(request);  // 清除session中的验证码
			yz=true;
		}
		// 判断验证码
		if (yz) {
			SysUser stu = sysUserService.getByAccount(user.getAccount());
	    	//账号不存在
	    	if(stu == null) {
	    		return ApiResponseBuilder.buildEntityError(BasicError.NOT_USER_ERROR);
	    	}
	    	//账号已停用
	    	if(stu.getUserStatus() == 1) {
	    		return ApiResponseBuilder.buildEntityError(BasicError.DISABLE_SERVICE_ERROR);
	    	}
	    	String sepwd = SaSecureUtil.md5BySalt(user.getPassword(), stu.getSalt());
	    	//密码错误
	    	if(!stu.getPassword().equals(sepwd)) {
	    		if(stu.getPwdErrNum()>=5) {
	    			//当天密码错误次数达上限，封号，第二天自动解封
	    			long disSec = DateUtil.between(new Date(), DateUtil.endOfDay(new Date()), DateUnit.SECOND);
	    			StpUtil.disable(user.getAccount(), disSec);
	    		}else {
	    			stu.setPwdErrNum(stu.getPwdErrNum()+1);
	            	sysUserService.updateById(stu);
	        		return ApiResponseBuilder.buildEntityError(BasicError.PASSWORD_ERROR);
	    		}
	    	}
	    	//判断账号是否被封禁
	    	if(StpUtil.isDisable(user.getAccount())) {
	    		return ApiResponseBuilder.buildEntityError(BasicError.PASSWORD_ERROR_OVER5);
	    	}
	    	//校验通过
	    	StpUtil.login(user.getAccount(), user.getClientType());
	    	stu.setToken(StpUtil.getTokenValueByLoginId(user.getAccount(), user.getClientType()));
	    	//更新最近登录时间、清除密码错误次数
	    	stu.setLastLoginTime(LocalDateTimeUtil.now());
	    	stu.setPwdErrNum(0);
	    	sysUserService.updateById(stu);
	    	//用户详情存缓存
	    	StpUtil.getTokenSession().set(SysConstant.USER_DETAIL_INFO, stu);
	        return ApiEntityResponse.ok(stu);
		} else {
			return ApiEntityResponse.error(BasicError.CAPTCHA_CODE_ERROR);
		}
	}
	
	

	/**
	 * 退出登陆
	 * 
	 * @return
	 */
	@ApiOperation(value = "退出登陆", notes = "退出登陆")
	@GetMapping("/Loginout")
	@ResponseBody
	public ApiResponse LoginOut(HttpServletRequest request, HttpServletResponse response) {
		// 在这里执行退出系统前需要清空的数据
		// ... 
		// 注销
		StpUtil.logout();
		return ApiResponse.ok();
	}

	/**** 页面测试 ****/
	@ApiOperation(value = "404页面", notes = "404页面")
	@GetMapping("Out404")
	public String Out404(HttpServletRequest request, HttpServletResponse response) {

		return "redirect:/error/404";
	}

	@GetMapping("Out403")
	@ApiOperation(value = "403页面", notes = "403页面")
	public String Out403(HttpServletRequest request, HttpServletResponse response) {

		return "redirect:/error/403";
	}

	@ApiOperation(value = "500页面", notes = "500页面")
	@GetMapping("Out500")
	public String Out500(HttpServletRequest request, HttpServletResponse response) {

		return "redirect:/error/500";
	}

	/**
	 * 权限测试跳转页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "权限测试跳转页面", notes = "权限测试跳转页面")
	@GetMapping("Outqx")
	@SaCheckPermission("system:user:asd")
	public String Outqx(HttpServletRequest request, HttpServletResponse response) {

		return "redirect:/error/500";
	}
	/**** 页面测试EDN ****/
}
